<?php
  include 'db-fajita.php';
  include 'functions.php';
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
  <head>
    <meta HTTP-EQUIV='content-type' CONTENT='text/html; charset=UTF-8'>
    <title>Factoid Modification Page</title>
    <link rel='stylesheet' type='text/css' href='css/style.css'>
    <script language='Javascript' type='text/javascript' src='js/functions.js'></script>
  </head>
  <body>
    <div class='main_div'>
    <form name='factoids' method='POST' action='index.php'>
<?php
  printf("    <input type='hidden' name='orderby_order' id='orderby_order' value='%s'>\n",
    $postOrderByOrder);
  printf("    <input type='hidden' name='orderby_column' id='orderby_column' value='%s'>\n",
    $postOrderByColumn);
  printf("    <input type='hidden' name='currentpage' id='currentpage' value='%s'>\n",
    $postCurrentPage);
  printf("    <input type='hidden' name='action' id='action' value='%s'>\n",
    $postAction);
  printf("    <input type='hidden' name='id' id='id' value=''>\n");
?>
    <table border='0' cellpadding='0' cellspacing='0' width='1165' class='content_header'>
      <tr>
        <td width='100' align='left' class='header_title'>SEARCH</td>
        <td width='67' align='right' class='header_title'>Status:&nbsp;</td>
        <td width='157' align='left'>
          <select name='status' id='status' onchange="getItem('currentpage').value='1';" class='form_element'>
<?php
  // Dynamically populate this element, and set the selected item to the previous value
  if ($postStatusValue == "" && $postAction == "") {
    print "            <option value='' selected>Please Select An Option</option>\n";
  }

  if ($postStatusValue == "all" || ($postStatusValue == "" && $postAction == "search")) {
    print "            <option value='all' selected>All Factoids</option>\n";
  } else {
    print "            <option value='all'>All Factoids</option>\n";
  }

  if ($postStatusValue == "active") {
    print "            <option value='active' selected>Active Factoids</option>\n";
  } else {
    print "            <option value='active'>Active Factoids</option>\n";
  }

  if ($postStatusValue == "deleted") {
    print "            <option value='deleted' selected>Deleted Factoids</option>\n";
  } else {
    print "            <option value='deleted'>Deleted Factoids</option>\n";
  }
?>
          </select>
        </td>
        <td width='97' align='right' class='header_title'>Availability:&nbsp;</td>
        <td width='157' align='left'>
          <select name='availability' id='availability' onchange="getItem('currentpage').value='1';" class='form_element'>
<?php
  // Dynamically populate this element, and set the selected item to the previous value
  if ($postAvailabilityValue == "" && $postAction == "") {
    print "            <option value='' selected>Please Select An Option</option>\n";
  }

  if ($postAvailabilityValue == "all" || ($postAvailabilityValue == "" && $postAction == "search")) {
    print "            <option value='all' selected>All Factoids</option>\n";
  } else {
    print "            <option value='all'>All Factoids</option>\n";
  }

  if ($postAvailabilityValue == "unlocked") {
    print "            <option value='unlocked' selected>Unlocked Factoids</option>\n";
  } else {
    print "            <option value='unlocked'>Unlocked Factoids</option>\n";
  }

  if ($postAvailabilityValue == "locked") {
    print "            <option value='locked' selected>Locked Factoids</option>\n";
  } else {
    print "            <option value='locked'>Locked Factoids</option>\n";
  }
?>
          </select>
        </td>
        <td width='97' align='right' class='header_title'>Search on:&nbsp;</td>
        <td width='127' align='left'>
          <select name='search_criteria' id='search_criteria' onchange="getItem('currentpage').value='1';" class='form_element'>
<?php
  // Dynamically populate this element, and set the selected item to the previous value
  if ($postSearchCriteria == "name") {
    print "            <option value='name' selected>Trigger Name</option>\n";
  } else {
    print "            <option value='name'>Trigger Name</option>\n";
  }

  // Too slow
  if ($postSearchCriteria == "value") {
    print "            <option value='value' selected>Trigger Value</option>\n";
  } else {
    print "            <option value='value'>Trigger Value</option>\n";
  }
?>
          </select>
        </td>
        <td width='177' align='center'><input type='text' name='search_value' id='search_value' maxlength='50' size='15' value='<?php echo $postSearchValue; ?>' onchange="getItem('currentpage').value='1';getItem('action').value='search';" class='form_element'></td>
<?php
  if ($postExactMatch == "on") {
    printf("        <td width='137' align='left'>Exact Match<input type='checkbox' name='match_type' id='match_type' class='form_element' checked></td>\n");
  } else {
    printf("        <td width='137' align='left'>Exact Match<input type='checkbox' name='match_type' id='match_type' class='form_element'></td>\n");
  }
?>
        <td width='50' align='center'><div id='go_button' class='middle_nav_button' onmouseover="changeClass('go_button','middle_nav_button_hover');" onmouseout="changeClass('go_button','middle_nav_button');" onclick="getItem('currentpage').value='1';getItem('action').value='search';document.factoids.submit();">Go</div></td>
      </tr>
    </table>
<?php
  // Built both sql queries, dynamically.
  // sqlselectquery is used to generate the listed results
  // sqlselectquery2 is used to generate the totals
  $sqlselectquery = "SELECT `id`, REPLACE(`factoid_key`, '\"', '\"\"') AS 'factoid_key', " .
    "REPLACE(`factoid_key`, ' #DEL#', '') AS 'factoid_key_cleaned', " .
    "`factoid_value`, FROM_UNIXTIME(`requested_time`) AS 'requested_time', " .
    "FROM_UNIXTIME(`created_time`) AS 'created_time', `requested_count`, `locked_time` FROM `" . $globalTableName . "` ";

  $sqlselectquery2 = "SELECT COUNT(`id`) AS 'id' FROM `" . $globalTableName . "` ";

  if ($postAction == "search") {
    $sqlwherequery = "WHERE 1 = 1 ";

    if ($postStatusValue == "active") {
      $sqlwherequery = $sqlwherequery . "AND `factoid_key` NOT LIKE '% #DEL#' ";
    } else if ($postStatusValue == "deleted") {
      $sqlwherequery = $sqlwherequery . "AND `factoid_key` LIKE '% #DEL#' ";
    }

    if ($postAvailabilityValue == "unlocked") {
      $sqlwherequery = $sqlwherequery . "AND (`locked_time` = 0 OR `locked_time` IS NULL) ";
    } else if ($postAvailabilityValue == "locked") {
      $sqlwherequery = $sqlwherequery . "AND `locked_time` > 0 ";
    }

    if ($postSearchValue != "" && $postSearchCriteria == "value") {
      if ($postExactMatch == "on") {
        $sqlwherequery = $sqlwherequery . "AND `factoid_value` = '" .
          mysql_real_escape_string($postSearchValue) . "' ";
      } else {
        $sqlwherequery = $sqlwherequery . "AND `factoid_value` LIKE '%" .
          mysql_real_escape_string($postSearchValue) . "%' ";
      }
    } else if ($postSearchValue != "" && $postSearchCriteria == "name") {
      if ($postExactMatch == "on") {
        $sqlwherequery = $sqlwherequery . "AND `factoid_key` = '" .
          mysql_real_escape_string($postSearchValue) . "' ";
      } else {
        $sqlwherequery = $sqlwherequery . "AND `factoid_key` LIKE '%" .
          mysql_real_escape_string($postSearchValue) . "%' ";
      }
    }
  }

  // Dynamic ordering
  if ($postOrderByColumn != "") {
    if ($postOrderByOrder != "") {
      $sqlorderquery = "ORDER BY `" . $postOrderByColumn . "` " .
        $postOrderByOrder . " ";
    } else {
      $sqlorderquery = "ORDER BY `" . $postOrderByColumn . "` ASC ";
    }
  } else {
    $sqlorderquery = "ORDER BY `factoid_key` ASC ";
  }

  if ($postCurrentPage != "") {
    $startindex = 10 * (intval($postCurrentPage) - 1);
    $sqllimit = "LIMIT " . $startindex . ",10";
  } else {
    $sqllimit = "LIMIT 0,10";
  }

  if ($postAction == "search") {
    $sqlquery2 = $sqlselectquery2 . $sqlwherequery . $sqlorderquery;
    $queryresult = mysql_query($sqlquery2);
    $row = mysql_fetch_array($queryresult);
    $totalnoofresults = intval($row["id"]);
    $numberofpages = ceil($totalnoofresults/10);
  } else {
    $totalnoofresults = 0;
    $numberofpages = 0;
  }

?>
    <table border='0' cellpadding='0' cellspacing='2' width='1165' class='content_header'>
      <tr>
        <td width='120' align='left' class='header_title'>NAVIGATION</td>
<?php
  // Build and display the navigation section
  if ($numberofpages == 0) {
    printf("        <td width='130' align='center' class='header_title'>%d Pages</td>\n",
           $numberofpages);
  } else if ($numberofpages == 1) {
    printf("        <td width='130' align='center' class='header_title'>%d Page:&nbsp;&nbsp;</td>\n",
           $numberofpages);
  } else {
    printf("        <td width='130' align='center' class='header_title'>%d Pages:&nbsp;&nbsp;</td>\n",
           $numberofpages);
  }

  print "        <td width='978' align='center' class='header_title'>\n";

  // Get the requested page right. I'll impact the rest of the routine
  if ($postCurrentPage != "") {
    $postCurrentPage = intval($postCurrentPage);
  } else {
    $postCurrentPage = 1;
  }

  // Only enable going back if there was more than one page, and the user was not on the first page already
  if ($numberofpages > 1 && $postCurrentPage > 1) {
    printf("          <div id='first_button' class='first_nav_button' onmouseover=\"changeClass('first_button','first_nav_button_hover');\" " .
           "onmouseout=\"changeClass('first_button','first_nav_button');\" onclick=\"gotopage(-1,%d);\">&lt;&lt;&nbsp;Previous</div>\n",
           $numberofpages);
  } else if ($numberofpages > 1) {
    printf("          <div id='first_button' class='first_nav_button' onmouseover=\"changeClass('first_button','first_nav_button_hover');\" " .
           "onmouseout=\"changeClass('first_button','first_nav_button');\">&lt;&lt;&nbsp;Previous</div>\n",
           $numberofpages);
  }

  if ($numberofpages <= 14) {
    // No ... is required
    $currentpage = 1;

    while($currentpage <= $numberofpages) {
      if ($postCurrentPage == $currentpage) {
        printf("          <div id='button%d' class='middle_nav_button_hover' onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
               "onmouseout=\"changeClass('button%d','middle_nav_button_hover');\">%d</div>\n",
               $currentpage, $currentpage, $currentpage, $currentpage);
      } else {
        printf("          <div id='button%d' class='middle_nav_button' onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
               "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
               "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\">%d</div>\n",
               $currentpage, $currentpage, $currentpage, $currentpage, $currentpage);
      }

      $currentpage = $currentpage + 1;
    }
  } else if ($numberofpages > 0) {
    // Preserve the posted (requested) page.
    // This variable will be iterated on, and its original value lost
    $currentpage = $postCurrentPage;

    if ($currentpage == 1) {
      // Add 11 items, for a total of 12 visible items. There will be a ...  before the last page shortcut
      $pageoffset = 11;
    } else if ($currentpage == 2) {
      // Add 10 items, for a total of 11 visible items. There will be a ...  before the last page shortcut
      // Since the '1' will also be present, it needs one more item
      $pageoffset = 10;
    } else if ($currentpage > 2 && ($currentpage + 11) >= $numberofpages) {
      $pageoffset = 11;
    } else if ($currentpage > 2) {
      // Add 9 items between the ... delimiter (first and last)
      $pageoffset = 9;
    }

    // Add the shortcut to the first page (clickable)
    if ($currentpage > 1) {
      print "          <div id='button0' class='middle_nav_button' onmouseover=\"changeClass('button0','middle_nav_button_hover');\" " .
            "onmouseout=\"changeClass('button0','middle_nav_button');\" onclick=\"getItem('currentpage').value='1';document.factoids.submit();\">1</div>\n";
    }

    // Add a delimiter (...) after the first page
    if ($currentpage > 2) {
      print "          <div id='button0_2' class='middle_nav_button' onmouseover=\"changeClass('button0_2','middle_nav_button_hover');\" " .
            "onmouseout=\"changeClass('button0_2','middle_nav_button');\">...</div>\n";
    }

    // This will determine the upper limit of the next loop
    if ($currentpage + $pageoffset > $numberofpages) {
      $maxpage = $numberofpages;
    } else {
      $maxpage = $currentpage + $pageoffset;
    }

    // In order to keep the number of items on the screen uniform, especially once you reach the end,
    // start the loop a little earlier (11 items before the last page, to be exact)
    if ($maxpage - $currentpage < 10 && $pageoffset == 11) {
      $currentpage = $maxpage - 11;
    }

    while($currentpage <= $maxpage) {
      if ($currentpage == $postCurrentPage) {
        // place the current page, highlighted
        printf("          <div id='button%d' class='middle_nav_button_hover'>%d</div>\n",
          $currentpage, $currentpage);
      } else {
        printf("          <div id='button%d' class='middle_nav_button' onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
               "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
               "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\">%d</div>\n",
               $currentpage, $currentpage, $currentpage, $currentpage, $currentpage);
      }

      $currentpage = $currentpage + 1;
    }

    if ($currentpage < ($numberofpages - 1)) {
      // We haven't reached the end yet
      // Place a '...' and a shortcut to the last page
      printf("          <div id='button%d' class='middle_nav_button' onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
             "onmouseout=\"changeClass('button%d','middle_nav_button');\">...</div>\n",
             $numberofpages + 1, $numberofpages + 1, $numberofpages + 1);
      printf("          <div id='button%d' class='middle_nav_button' onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
             "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
             "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\">%d</div>\n",
             $numberofpages + 2, $numberofpages + 2, $numberofpages + 2, $numberofpages, $numberofpages);
    }
  }

  if ($numberofpages > 1 && $postCurrentPage != $numberofpages) {
    // A functional 'next' button is required
    printf("          <div id='last_nav_button' class='last_nav_button' onmouseover=\"changeClass('last_nav_button','last_nav_button_hover');\" " .
           "onmouseout=\"changeClass('last_nav_button','last_nav_button');\" onclick=\"gotopage(1,%d);\">Next&nbsp;&gt;&gt;</div>\n",
           $numberofpages);
  } else if ($numberofpages > 1 && $postCurrentPage == $numberofpages) {
    // A 'next' button is added, to keep the esthetics. It's non-functional
    printf("          <div id='last_nav_button' class='last_nav_button' onmouseover=\"changeClass('last_nav_button','last_nav_button_hover');\" " .
           "onmouseout=\"changeClass('last_nav_button','last_nav_button');\">Next&nbsp;&gt;&gt;</div>\n");
  }
?>
        </td>
      </tr>
    </table>
<?php
  if ($postAction == "search") {
    $sqlquery = $sqlselectquery . $sqlwherequery . $sqlorderquery . $sqllimit;
    $queryresult = mysql_query($sqlquery);
    $num_rows = mysql_num_rows($queryresult);
  } else {
    $num_rows = 0;
  }

  if ($num_rows > 0) {
    print "    <table border='0' cellpadding='0' cellspacing='2' width='1165' class='content_header'>\n";
    print "      <tr>\n";
    print "        <td width='120' align='left' class='header_title'>MASS UPDATES</td>\n";
    printf("        <td width='60' align='center' class='header_title'><div id='visibility-%d' class='deleted' " .
           "onclick=\"deleteRestoreAllFactoids('batchdelete');\"></div></td>\n",
           0);
    printf("        <td width='60' align='center' class='header_title'><div id='visibility-%d' class='active' " .
           "onclick=\"deleteRestoreAllFactoids('batchactivate');\"></div></td>\n",
           1);
    printf("        <td width='60' align='center' class='header_title'><div id='lock-%d' class='locked' " .
           "onclick=\"lockUnlockAllFactoids('batchlock');\"></div></td>\n",
           0);
    printf("        <td width='60' align='center' class='header_title'><div id='lock-%d' class='unlocked' " .
           "onclick=\"lockUnlockAllFactoids('batchunlock');\"></div></td>\n",
           1);
    printf("        <td width='60' align='center' class='header_title'><div id='erase-%d' class='eraser' " .
           "onclick=\"eraseRestoreAllFactoids('batcherase');\"></div></td>\n",
           0);
    print "        <td width='733' align='center' class='header_title'><span>&nbsp;</span></td>\n";
    print "      </tr>\n";
    print "    </table>\n";
  }

  if ($postAction == "") {
    print "    <table border='0' cellpadding='0' cellspacing='0' width='1165' class='content_header'>\n";
    print "      <tr>\n";
    print "        <td colspan='9' width='1165' align='center' class='col_yellow'>Please select search or filtering parameters above to start</td>\n";
    print "      </tr>\n";
  } else if ($num_rows == 0) {
    print "    <table border='0' cellpadding='0' cellspacing='0' width='1165' class='content_header'>\n";
    print "      <tr>\n";
    print "        <td colspan='9' width='1165' align='center' class='col_yellow'>No Results Found</td>\n";
    print "      </tr>\n";
  } else {
    print "    <table border='0' cellpadding='0' cellspacing='0' width='1165' class='content_header'>\n";
    print "      <tr>\n";
    print "        <td width='60' align='center' class='header_title'>Exclude</td>\n";
    print "        <td width='60' align='center' class='header_title'>Visible</td>\n";
    print "        <td width='60' align='center' class='header_title'>Locked</td>\n";
    print "        <td width='260' align='center' class='header_title'><span " .
          "onclick=\"changeSortingOrder('factoid_key');document.factoids.submit();\">Trigger</span></td>\n";
    print "        <td width='395' align='center' class='header_title'><span " .
          "onclick=\"changeSortingOrder('factoid_value');document.factoids.submit();\">Value</span></td>\n";
    print "        <td width='60' align='center' class='header_title'>Revert</td>\n";
    print "        <td width='90' align='center' class='header_title'><span " .
          "onclick=\"changeSortingOrder('created_time');document.factoids.submit();\">Created</span></td>\n";
    print "        <td width='90' align='center' class='header_title'><span " .
          "onclick=\"changeSortingOrder('requested_time');document.factoids.submit();\">Accessed</span></td>\n";
    print "        <td width='80' align='center' class='header_title'><span " .
          "onclick=\"changeSortingOrder('requested_count');document.factoids.submit();\">Requests</span></td>\n";
    print "      </tr>\n";
    print "      <tr>\n";
    print "        <td colspan='9' class='header_title'>&nbsp;</td>\n";
    print "      </tr>\n";

    $rowcount = 0;

    while ($row = mysql_fetch_array($queryresult)) {
      print "      <tr>\n";
      printf("        <td align='center' class='col_yellow'><input type='checkbox' name='exclude%d' id='exclude%d'></td>\n",
             $row["id"], $row["id"]);

      if (substr_count($row["factoid_key"], " #DEL#") > 0) {
        printf("        <td align='center' class='col_yellow'><div id='visibility%d' class='deleted' onclick=\"alterFactoidState(%d);\"></div></td>\n",
               $row["id"], $row["id"]);
      } else {
        printf("        <td align='center' class='col_yellow'><div id='visibility%d' class='active' onclick=\"alterFactoidState(%d);\"></div></td>\n",
               $row["id"], $row["id"]);
      }

      if ($row["locked_time"] > 0) {
        printf("        <td align='center' class='col_yellow'><div id='lock%d' class='locked' onclick=\"lockUnlockFactoid(%d);\"></div></td>\n",
               $row["id"], $row["id"]);
      } else {
        printf("        <td align='center' class='col_yellow'><div id='lock%d' class='unlocked' onclick=\"lockUnlockFactoid(%d);\"></div></td>\n",
               $row["id"], $row["id"]);
      }

      $factoidkey = str_replace("\"", "&quot;", $row["factoid_key"]);

      $factoidkeycleaned = str_replace("\"", "&quot;", $row["factoid_key_cleaned"]);
      $factoidkeycleaned = str_replace("<", "&lt;", $factoidkeycleaned);
      $factoidkeycleaned = str_replace(">", "&gt;", $factoidkeycleaned);

      printf("        <td align='center' class='col_yellow'><input type='hidden' name='key%d' id='key%d' value=\"%s\">" .
             "<input type='hidden' name='id%d' id='id%d' value=\"%s\">%s</td>\n",
        $row["id"], $row["id"], $factoidkey, $rowcount, $rowcount,
        $row["id"], $factoidkeycleaned);

      $numofrowsrequired = ceil(strlen($row["factoid_value"]) / 70);
      $factoidvalue = str_replace("<", "&lt;", $row["factoid_value"]);
      $factoidvalue = str_replace(">", "&gt;", $factoidvalue);

      if ($row["locked_time"] > 0) {
        printf("        <td align='center' class='col_yellow'><textarea name='value%d' id='value%d' cols='50' rows='%d' class='disabled_field' " .
               "onchange=\"updateFactoidValue('%d')\">%s</textarea></td>\n",
               $row["id"], $row["id"], $numofrowsrequired, $row["id"], $factoidvalue);
      } else {
        printf("        <td align='center' class='col_yellow'><textarea name='value%d' id='value%d' cols='50' rows='%d' class='form_element' " .
               "onchange=\"updateFactoidValue('%d')\">%s</textarea></td>\n",
               $row["id"], $row["id"], $numofrowsrequired, $row["id"], $factoidvalue);
      }

      //printf("        <td align='center' class='col_yellow'><div id='revert%d' class='revert' onclick=\"recoverFactoidValue(%d);\"></div></td>\n",
      //       $row["id"], $row["id"]);
      printf("        <td align='center' class='col_yellow'><div id='revert%d' class='revert_dark'></div></td>\n",
             $row["id"]);
      printf("        <td align='center' class='col_yellow'>%s</td>\n",
             str_replace(" ", "<br>", $row["created_time"]));
      printf("        <td align='center' class='col_yellow'>%s</td>\n",
             str_replace(" ", "<br>", $row["requested_time"]));
      printf("        <td align='center' class='col_yellow'>%s</td>\n",
             $row["requested_count"]);
      print "      </tr>\n";

      $rowcount = $rowcount + 1;
    }
  }
?>
    </table>
    </form>
    </div>
  </body>
</html>
